package com.it.mmx.memory.circuit.breaker.interceptor;

import com.it.mmx.memory.circuit.breaker.config.MemoryCircuitBreakerProperties;
import com.it.mmx.memory.circuit.breaker.monitor.SystemMemoryMonitor;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;

/**
 * 内存熔断拦截器（Spring MVC）
 * @author 刘仲
 */
public class MemoryCircuitBreakerInterceptor implements HandlerInterceptor {

    private final SystemMemoryMonitor memoryMonitor;
    private final MemoryCircuitBreakerProperties properties;
    private final PathMatcher pathMatcher = new AntPathMatcher();

    public MemoryCircuitBreakerInterceptor(SystemMemoryMonitor memoryMonitor, MemoryCircuitBreakerProperties properties) {
        this.memoryMonitor = memoryMonitor;
        this.properties = properties;
    }

    @Override
    public boolean preHandle( HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        String requestPath = request.getRequestURI();

        // 检查当前路径是否需要熔断
        boolean isPathMatched = properties.getApiPaths().stream()
                .anyMatch(pattern -> pathMatcher.match(pattern, requestPath));

        if (isPathMatched && memoryMonitor.isNeedCircuitBreak()) {
            // 触发熔断：返回503服务不可用
            response.setStatus(HttpStatus.SERVICE_UNAVAILABLE.value());
            response.setContentType("application/json;charset=UTF-8");
            String message = String.format(
                    "{\"code\":503,\"message\":\"系统内存不足（剩余%.2f%%），已触发熔断保护\"}",
                    memoryMonitor.getRemainingMemoryPercent()
            );
            response.getWriter().write(message);
            return false; // 阻止请求继续执行
        }

        return true; // 正常放行
    }
}
